import React, { useState, useEffect } from 'react';
import { Layout, Flex, Row, Col, theme, notification } from 'antd';
import LineChart from './project/line_chart';
import CalendarChart, { CalendarChartData } from './project/scatter_calendar_chart';
import AppList from './project/app_list_chart';
import PortList from './project/port_list_chart';
import ProjectTable from './project/project_table';
import { fetchApi } from '../general/api';

const { Content, Sider } = Layout;

const App: React.FC = () => {
    const [healthCalendarData, sethealthCalendarData] = useState<CalendarChartData[]>([]);
    const [appsDataListData, setappsDataListData] = useState([]);
    const [portListData, setportListData] = useState([]);
    const initialDatasets = {
        cpu: {
            data_time: [],
            data: [],
        },
        memory: {
            data_time: [],
            data: [],
        },
        disk: {
            data_time: [],
            data: [],
        },
    };
    // 定义用于CPU、内存、硬盘数据  
    const [datasets, setDatasets] = useState(initialDatasets);

    const project_click = async (project_id: string) => {
        // 清空数据
        // setDatasets(initialDatasets);
        // sethealthCalendarData([]);
        // setappsDataListData([]);
        // setportListData([]);

        //重新请求
        await fetchProjectOptions(project_id)
        await calendarProjectOptions(project_id)
        await ProjectAppInfoOptions(project_id)
        await ProjectPortListOptions(project_id)
    }

    // 请求资源情况
    const fetchProjectOptions = async (key: string) => {
        try {
            const response_data = await fetchApi(`/easymonitor/api/get_project_base_merit_dict?project_id=${key}`); // 使用 fetchApi  
            setDatasets(response_data);
            notification.success({
                message: '请求成功', description: '基础监控数据更新成功。', duration: 2 // 2秒后自动关闭  
            });
        } catch (error) {
            notification.error({
                message: '请求失败', description: '基础监控数据查询失败:' + error, duration: 5
            });
        }
    };

    // 请求资源情况
    const calendarProjectOptions = async (key: string) => {
        try {
            const response_data = await fetchApi(`/easymonitor/api/project_healthcalendar?project_id=${key}`); // 使用 fetchApi  
            sethealthCalendarData(response_data);

            console.log(response_data)

            notification.success({
                message: '请求成功', description: '健康日历查询成功。', duration: 2 // 2秒后自动关闭  
            });
        } catch (error) {
            notification.error({
                message: '请求失败', description: '健康日历查询失败:' + error, duration: 2
            });
        }
    };

    // 请求应用信息情况
    const ProjectAppInfoOptions = async (key: string) => {
        try {
            const response_data = await fetchApi(`/easymonitor/api/project_app_runinfo?project_id=${key}`); // 使用 fetchApi  
            setappsDataListData(response_data);

            notification.success({
                message: '请求成功', description: '应用信息查询成功。', duration: 2 // 2秒后自动关闭  
            });
        } catch (error) {
            notification.error({
                message: '请求失败', description: '应用信息查询失败:' + error, duration: 2
            });
        }
    };

    // 请求应用信息情况
    const ProjectPortListOptions = async (key: string) => {
        try {
            const response_data = await fetchApi(`/easymonitor/api/project_port_runinfo?project_id=${key}`); // 使用 fetchApi  
            setportListData(response_data);

            notification.success({
                message: '请求成功', description: '应用信息查询成功。', duration: 2 // 2秒后自动关闭  
            });
        } catch (error) {
            notification.error({
                message: '请求失败', description: '应用信息查询失败:' + error, duration: 2
            });
        }
    };

    const [splitterHeight, setSplitterHeight] = useState(window.innerHeight - 200);

    const updateHeight = () => {
        setSplitterHeight(window.innerHeight - 100);
    };

    useEffect(() => {
        // 监听窗口大小变化  
        window.addEventListener('resize', updateHeight);

        // 清除事件监听器  
        return () => {
            window.removeEventListener('resize', updateHeight);
        };
    }, []);

    const layoutStyle = {
        borderRadius: 8,
        overflow: 'hidden'
    };

    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1  
    const yearMonth = `${year}-${month}`;

    const {
        token: { colorBgContainer, borderRadiusLG },
    } = theme.useToken();

    return (
        <Layout style={layoutStyle}>
            <Sider width="10%" style={{ height: splitterHeight, background: colorBgContainer, borderRadius: borderRadiusLG }}>
                <ProjectTable onRowClick={project_click} />
            </Sider>
            <Content>
                <Flex gap="middle" vertical>
                    <Flex>
                        <Row style={{ width: "100%", height: 300 }}>
                            <Col span={8} className="flex-item">
                                <Flex>
                                    <LineChart
                                        labels={datasets.cpu.data_time}
                                        datasets={datasets.cpu.data}
                                        xAxisTitle="时间"
                                        yAxisTitle="负载:%"
                                        chartTitle="CPU 使用情况"
                                    />
                                </Flex>
                            </Col>
                            <Col span={8} className="flex-item">
                                <Flex>
                                    <LineChart
                                        labels={datasets.memory.data_time}
                                        datasets={datasets.memory.data}
                                        xAxisTitle="时间"
                                        yAxisTitle="负载:%"
                                        chartTitle="内存 使用情况"
                                    />
                                </Flex>
                            </Col>
                            <Col span={8} className="flex-item">
                                <Flex>
                                    <LineChart
                                        labels={datasets.disk.data_time}
                                        datasets={datasets.disk.data}
                                        xAxisTitle="时间"
                                        yAxisTitle="负载:%"
                                        chartTitle="硬盘 使用情况"
                                    />
                                </Flex>
                            </Col>
                        </Row>
                    </Flex>
                    <Flex>
                        <Row className="flex-row" style={{ width: "100%", height: 300 }}>
                            <Col span={5} className="flex-item">
                                <CalendarChart
                                    cellSize={[40, 40]}
                                    dateRange={[yearMonth]}
                                    chartTitle="健康日历"
                                    data={healthCalendarData}
                                />
                            </Col>
                            <Col span={14} className="flex-item">
                                <AppList data={appsDataListData} chartTitle="应用运行" />
                            </Col>
                            <Col span={5} className="flex-item">
                                <PortList data={portListData} chartTitle="任务列表" />
                            </Col>
                        </Row>
                    </Flex>
                </Flex>
            </Content>
        </Layout >
    );
};

export default App;